package com.cloudcc.mobile.view.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;

@SuppressLint("SetJavaScriptEnabled")
public class WebActivtiy extends BaseActivity {
	public static final String ARG_PLANET_NUMBER = "planet_number";
	private PullToRefreshWebView weixinview;
	private ImageView fanhui;
	private ImageView shuaxin;
	private RelativeLayout caozuo;
	private CustomProgressDialog progressDialog;
	private NetWork net;
	private String urlString;
	private SharePreferece share;
	private ValueCallback<Uri> mUploadMessage;
	private final int OPEN_RESULT = 1;
	private final int PINK_RESULT = 2;
	private String filePath;
	private Uri uri;
	private Context context;
	private LinearLayout network;
	private ImageView menubtn;
	private RelativeLayout webview;
	private WebView weixin;
	/** 显示格式化日期模板 */
	private final static String DATE_FORMAT_STR = "yyyy年MM月dd日 HH:mm";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		try {
			context = this;
			setView();
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.webview2;
	}

	private void setView() {
		weixinview = (PullToRefreshWebView) findViewById(R.id.weixin);
		weixin = weixinview.getRefreshableView();
		fanhui = (ImageView) findViewById(R.id.fanhui);
		shuaxin = (ImageView) findViewById(R.id.shuaxin);
		menubtn = (ImageView) findViewById(R.id.webview_menubtn);
		caozuo = (RelativeLayout) findViewById(R.id.caozuo);
		caozuo.setVisibility(View.GONE);
		webview = (RelativeLayout) findViewById(R.id.webview_yemian);
		network = (LinearLayout) findViewById(R.id.network_bad);
		share = new SharePreferece(context);
		caozuo.setVisibility(View.GONE);
		weixin.setVisibility(View.GONE);
		progressDialog = CustomProgressDialog.createDialog(context);
		webview();
		setLastUpdateTime();
	}

	/**
	 * webview操作类
	 */
	public void webview() {
		weixin.requestFocus();
		weixin.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
		weixin.loadUrl(AppContext.urlString);
		weixin.reload();
		WebSettings webstting = weixin.getSettings();
		webstting.setJavaScriptEnabled(true);
		// 设置可以访问文件
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		weixin.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				LogUtils.d("webview", "加载开始" + url);
				urlString = url;
				startProgressDialog();
				if (url.equals(AppContext.indexUrl)) {
					WebActivtiy.this.finish();
					weixin.stopLoading();
					return;
				}
				if (url.equals(UrlTools.loginurl)) {
					Intent intent = new Intent(UrlTools.loginurl);
					context.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				LogUtils.d("webview", "加载完成" + url);
				// 加载完了再调用js登录代码
				stopProgressDialog();
				setLastUpdateTime();// 刷新时间
				if (AppContext.isError) {
					weixin.setVisibility(View.GONE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.VISIBLE);
					if (!AppContext.isFirst) {
						AppContext.isError = false;
					}
					AppContext.isFirst = false;
				} else {
					AppContext.isFirst = true;
					weixin.setVisibility(View.VISIBLE);
					caozuo.setVisibility(View.GONE);
					network.setVisibility(View.GONE);
				}
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				LogUtils.d("webview", "跳转开始" + url);
				if (url.equals(UrlTools.weixinUrl + UrlTools.wxIndexUrl)) {
					// AppContext.menu.toggle();
					WebActivtiy.this.finish();
					return true;
				} else {
					// 自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}

			public void onReceivedSslError(WebView view,
					android.webkit.SslErrorHandler handler,
					android.net.http.SslError error) {
				handler.proceed();
			};

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		});
		weixin.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				DialogUtils dialogutils = new DialogUtils(context);
				dialogutils.showUpdateDialog(context, "网页提示", message);
				dialogutils.setOnDoClicktListener(new OnDoClickListener() {
					@Override
					public void confirm() {
						result.confirm();
					}

					@Override
					public void cancel() {
						result.cancel();
					}
				});
				return true;
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType) {
				if (mUploadMessage != null)
					return;
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult(Intent.createChooser(i, "选择文件"),
						PINK_RESULT);
			}

			// For Android > 4.1.1
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType, String capture) {
				openFileChooser(uploadMsg, acceptType);
			}

			// For Android < 3.0
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooser(uploadMsg, "");
			}
		});
	}

	protected void setLastUpdateTime() {
		weixinview.setLastUpdatedLabel(new SimpleDateFormat(DATE_FORMAT_STR,
				Locale.CHINA).format(new Date()));
	}

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == PINK_RESULT) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null || resultCode != this.RESULT_OK ? null
					: intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}
	}

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(context);
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
			// progressDialog.setMessage("正在加载中...");
		}
		progressDialog.show();
	}

	/**
	 * 停止dialog
	 */
	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * 监听 mWebView.goBack(); //后退 mWebView.goForward();//前进 mWebView.reload();
	 * //刷新
	 */
	private void addListener() {
		weixinview.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<WebView> refreshView) {
				weixin.reload();
				weixinview.onPullDownRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
			}
		});
		network.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
				AppContext.isFirst = true;
				AppContext.isError = false;
			}
		});
		menubtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// AppContext.menu.toggle();
			}
		});
		fanhui.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (urlString.equals(UrlTools.weixinUrl + UrlTools.menuurl)) {
					weixin.reload(); // 刷新
				} else {
					weixin.goBack(); // 后退
				}
			}
		});
		shuaxin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				weixin.reload(); // 刷新
			}
		});

	}
}